package com.example.demo.controller;

import com.example.demo.crypto.DingCallbackCrypto;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import java.util.LinkedHashMap;
import java.io.FileWriter;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
public class DingTalkController {

    private final String token = "qcXRqzbFH";
    private final String aesKey = "l29ELAndbgrhOqMhnowKhHdFSagj0huzIv5qpiauye3";
    private final String corpId = "dingbqwkle9kpq3qnona";
    private final String DATA_FILE = "/www/wwwroot/ceshi.cn/data.json";

    @PostMapping("/test")
    public Map<String, String> test(
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature,
            @RequestBody String body) {
        try {
            System.out.println("Received params:");
            System.out.println("signature: " + signature);
            System.out.println("timestamp: " + timestamp);
            System.out.println("nonce: " + nonce);
            System.out.println("msg_signature: " + msgSignature);
            System.out.println("body: " + body);
            
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(token, aesKey, corpId);
            
            // 如果有请求体，尝试解密并保存
            if (body != null && !body.isEmpty()) {
                JSONObject jsonObject = JSON.parseObject(body);
                String encrypt = jsonObject.getString("encrypt");
                if (encrypt != null) {
                    // 解密消息
                    String decrypted = callbackCrypto.getDecryptMsg(msgSignature, timestamp, nonce, encrypt);
                    System.out.println("Decrypted message: " + decrypted);
                    
                    // 创建包含时间戳的记录
                    JSONObject record = new JSONObject();
                    record.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                    record.put("data", JSON.parseObject(decrypted));
                    
                    // 追加到文件
                    try (FileWriter writer = new FileWriter(DATA_FILE, true)) {
                        writer.write(record.toJSONString() + "\n");
                    }
                }
            }
            
            // 返回加密的success
            Map<String, String> encryptedMap = callbackCrypto.getEncryptedMap("success");
            
            Map<String, String> responseMap = new LinkedHashMap<>();
            responseMap.put("msg_signature", encryptedMap.get("msg_signature"));
            responseMap.put("timeStamp", encryptedMap.get("timeStamp"));
            responseMap.put("nonce", encryptedMap.get("nonce"));
            responseMap.put("encrypt", encryptedMap.get("encrypt"));
            
            return responseMap;
            
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorMap = new LinkedHashMap<>();
            errorMap.put("msg_signature", "");
            errorMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
            errorMap.put("nonce", "");
            errorMap.put("encrypt", "");
            return errorMap;
        }
    }

    @PostMapping("/")
    public Map<String, String> handleCallback(
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String reqTimestamp,
            @RequestParam(value = "nonce", required = false) String reqNonce,
            @RequestParam(value = "msg_signature", required = false) String reqMsgSignature,
            @RequestBody String body) {
        try {
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(token, aesKey, corpId);
            Map<String, String> encryptedMap = callbackCrypto.getEncryptedMap("success");
            
            Map<String, String> responseMap = new LinkedHashMap<>();
            responseMap.put("msg_signature", encryptedMap.get("msg_signature"));
            responseMap.put("timeStamp", encryptedMap.get("timeStamp"));
            responseMap.put("nonce", encryptedMap.get("nonce"));
            responseMap.put("encrypt", encryptedMap.get("encrypt"));
            
            return responseMap;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(token, aesKey, corpId);
                Map<String, String> encryptedMap = callbackCrypto.getEncryptedMap("success");
                
                Map<String, String> responseMap = new LinkedHashMap<>();
                responseMap.put("msg_signature", encryptedMap.get("msg_signature"));
                responseMap.put("timeStamp", encryptedMap.get("timeStamp"));
                responseMap.put("nonce", encryptedMap.get("nonce"));
                responseMap.put("encrypt", encryptedMap.get("encrypt"));
                
                return responseMap;
            } catch (Exception ex) {
                ex.printStackTrace();
                Map<String, String> errorMap = new LinkedHashMap<>();
                errorMap.put("msg_signature", "");
                errorMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
                errorMap.put("nonce", "");
                errorMap.put("encrypt", "");
                return errorMap;
            }
        }
    }
    
    // 添加测试接口
    @GetMapping("/test/encrypt")
    public Map<String, String> testEncrypt(@RequestParam String text) {
        try {
            DingCallbackCrypto crypto = new DingCallbackCrypto(token, aesKey, corpId);
            return crypto.getEncryptedMap(text);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("加密失败", e);
        }
    }
    
    @PostMapping("/test/decrypt")
    public String testDecrypt(@RequestParam String signature,
                            @RequestParam String timestamp,
                            @RequestParam String nonce,
                            @RequestParam String encrypt) {
        try {
            DingCallbackCrypto crypto = new DingCallbackCrypto(token, aesKey, corpId);
            return crypto.getDecryptMsg(signature, timestamp, nonce, encrypt);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解密失败", e);
        }
    }
} 